package com.shawn.springboot.integeration.common.config.exception;

import com.shawn.springboot.integeration.common.model.GenericResponse;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shawn
 * @description: 全局异常处理器
 * @date 2023/11/26
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    // 运行时异常
    @ExceptionHandler(RuntimeException.class)
    public GenericResponse notFount(RuntimeException e)
    {
        log.error("运行时异常:", e);
        return GenericResponse.error("运行时异常:" + e.getMessage());
    }

    // 系统异常
    @ExceptionHandler(Exception.class)
    public GenericResponse handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return GenericResponse.error("服务器错误，请联系管理员");
    }

    /**
     * 权限校验失败 如果请求为ajax返回json，普通请求跳转页面
     *
     * @param request 请求
     * @param e       授权异常
     * @return 返回值
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(HttpServletRequest request, AuthorizationException e) {
        log.error(e.getMessage(), e);
        return GenericResponse.error("权限不足");

    }
}
